<script setup lang="ts">
import { onMounted, ref } from 'vue';

import {
  ElButton,
  ElCard,
  ElCheckbox,
  ElCheckboxGroup,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElPagination,
  ElTable,
  ElTableColumn,
} from 'element-plus';

import {
  assignVehiclesApi,
  checkPhoneExistsApi,
  createDriverApi,
  getDriversApi,
  updateDriverApi,
} from '#/api/drivers';
import { getAvailableVehiclesApi } from '#/api/vehicle';

// 类型定义
interface Driver {
  driverId: number;
  fullName: string;
  phoneNumber: string;
  licenseLevel?: string;
  status: string;
  emergencyContact?: string;
  firstLicenseDate?: string;
  createTime: string;
  updateTime: string;
}

interface Vehicle {
  vehicleId: number;
  licensePlate: string;
  model: string;
  status: string;
  driverId?: number;
  driverName?: string;
}

// 响应式数据
const loading = ref(false);
const formVisible = ref(false);
const assignVisible = ref(false);
const isEdit = ref(false);
const currentDriver = ref<Driver | null>(null);

// 筛选表单
const searchForm = ref({
  fullName: '',
  phoneNumber: '',
});

// 分页数据
const pagination = ref({
  page: 1,
  pageSize: 20,
  total: 0,
});

// 司机列表
const driverList = ref<Driver[]>([]);

// 司机表单
const driverForm = ref({
  fullName: '',
  phoneNumber: '',
  licenseLevel: '',
  emergencyContact: '',
  firstLicenseDate: '',
});

// 表单验证规则
const formRules = ref({
  fullName: [{ required: true, message: '请完善必填信息', trigger: 'blur' }],
  phoneNumber: [{ required: true, message: '请完善必填信息', trigger: 'blur' }],
});

// 可用车辆列表
const availableVehicles = ref<Vehicle[]>([]);
const selectedVehicleIds = ref<number[]>([]);

// 计算属性
const formTitle = ref('新增司机');

// 方法定义
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await getDriversApi({
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      fullName: searchForm.value.fullName,
      phoneNumber: searchForm.value.phoneNumber,
    });

    if (response.code === 200) {
      driverList.value = response.data.list;
      pagination.value.total = response.data.total;
    } else {
      ElMessage.error('获取司机列表失败');
    }
  } catch {
    ElMessage.error('获取司机列表失败');
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.value.page = 1; // 重置到第一页
  fetchData();
};

const handleReset = () => {
  searchForm.value = {
    fullName: '',
    phoneNumber: '',
  };
  pagination.value.page = 1;
  fetchData();
};

const handleAdd = () => {
  isEdit.value = false;
  formTitle.value = '新增司机';
  driverForm.value = {
    fullName: '',
    phoneNumber: '',
    licenseLevel: '',
    emergencyContact: '',
    firstLicenseDate: '',
  };
  formVisible.value = true;
};

const handleEdit = (row: Driver) => {
  isEdit.value = true;
  formTitle.value = '编辑司机';
  currentDriver.value = row;
  driverForm.value = {
    fullName: row.fullName,
    phoneNumber: row.phoneNumber,
    licenseLevel: row.licenseLevel || '',
    emergencyContact: row.emergencyContact || '',
    firstLicenseDate: row.firstLicenseDate || '',
  };
  formVisible.value = true;
};

const handleAssign = async (row: Driver) => {
  currentDriver.value = row;
  try {
    const response = await getAvailableVehiclesApi();
    if (response.code === 200) {
      availableVehicles.value = response.data;
      // 设置已分配车辆的选中状态
      selectedVehicleIds.value = availableVehicles.value
        .filter((vehicle) => vehicle.driverId === row.driverId)
        .map((vehicle) => vehicle.vehicleId);
      assignVisible.value = true;
    } else {
      ElMessage.error('获取可用车辆列表失败');
    }
  } catch {
    ElMessage.error('获取可用车辆列表失败');
  }
};

const handleFormSubmit = async () => {
  // 验证必填字段
  if (!driverForm.value.fullName || !driverForm.value.phoneNumber) {
    ElMessage.error('请完善必填信息');
    return;
  }

  // 检查联系电话是否已存在
  try {
    const checkResponse = await checkPhoneExistsApi({
      phoneNumber: driverForm.value.phoneNumber,
      excludeId: isEdit.value ? currentDriver.value?.driverId : undefined,
    });

    if (checkResponse.data) {
      ElMessage.error('该联系电话已存在，请更换');
      return;
    }
  } catch {
    ElMessage.error('检查联系电话失败');
    return;
  }

  try {
    if (isEdit.value && currentDriver.value) {
      // 更新司机
      const response = await updateDriverApi(
        currentDriver.value.driverId,
        driverForm.value,
      );
      if (response.code === 200) {
        ElMessage.success('更新司机成功');
        formVisible.value = false;
        fetchData();
      } else {
        ElMessage.error('更新司机失败');
      }
    } else {
      // 新增司机
      const response = await createDriverApi(driverForm.value);
      if (response.code === 200) {
        ElMessage.success('创建司机成功');
        formVisible.value = false;
        fetchData();
      } else {
        ElMessage.error('创建司机失败');
      }
    }
  } catch {
    ElMessage.error('操作失败');
  }
};

const handleAssignSubmit = async () => {
  if (!currentDriver.value) return;

  try {
    const response = await assignVehiclesApi(currentDriver.value.driverId, {
      vehicleIds: selectedVehicleIds.value,
    });

    if (response.code === 200) {
      ElMessage.success('分配车辆成功');
      assignVisible.value = false;
      fetchData();
    } else {
      ElMessage.error('分配车辆失败');
    }
  } catch {
    ElMessage.error('分配车辆失败');
  }
};

const handlePageChange = (page: number) => {
  pagination.value.page = page;
  fetchData();
};

const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize;
  pagination.value.page = 1;
  fetchData();
};

// 生命周期
onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="driver-management">
    <!-- 筛选区域 -->
    <ElCard class="filter-card">
      <ElForm :model="searchForm" inline>
        <ElFormItem label="姓名">
          <ElInput
            v-model="searchForm.fullName"
            placeholder="支持模糊搜索"
            clearable
            @keyup.enter="handleSearch"
          />
        </ElFormItem>
        <ElFormItem label="联系电话">
          <ElInput
            v-model="searchForm.phoneNumber"
            placeholder="支持模糊搜索"
            clearable
            @keyup.enter="handleSearch"
          />
        </ElFormItem>
        <ElFormItem>
          <ElButton type="primary" @click="handleSearch">查询</ElButton>
          <ElButton @click="handleReset">重置</ElButton>
        </ElFormItem>
      </ElForm>
    </ElCard>

    <!-- 操作区域 -->
    <ElCard class="action-card">
      <ElButton type="primary" @click="handleAdd">新增司机</ElButton>
    </ElCard>

    <!-- 数据表格 -->
    <ElCard class="data-card">
      <ElTable :data="driverList" :loading="loading" style="width: 100%">
        <ElTableColumn prop="fullName" label="姓名" />
        <ElTableColumn prop="phoneNumber" label="联系电话" />
        <ElTableColumn prop="licenseLevel" label="驾照等级" />
        <ElTableColumn prop="status" label="状态">
          <template #default="{ row }">
            <span
              :class="
                row.status === '在职' ? 'status-active' : 'status-inactive'
              "
            >
              {{ row.status }}
            </span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" width="150">
          <template #default="{ row }">
            <ElButton type="text" @click="handleEdit(row)">修改</ElButton>
            <ElButton type="text" @click="handleAssign(row)">分配车辆</ElButton>
          </template>
        </ElTableColumn>
      </ElTable>

      <!-- 分页组件 -->
      <ElPagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[15, 20, 25, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handlePageChange"
      />
    </ElCard>

    <!-- 新增/编辑司机弹框 -->
    <ElDialog
      v-model="formVisible"
      :title="formTitle"
      width="500px"
      @close="formVisible = false"
    >
      <ElForm :model="driverForm" :rules="formRules" label-width="100px">
        <ElFormItem label="姓名" prop="fullName">
          <ElInput v-model="driverForm.fullName" placeholder="请输入司机姓名" />
        </ElFormItem>
        <ElFormItem label="联系电话" prop="phoneNumber">
          <ElInput
            v-model="driverForm.phoneNumber"
            placeholder="请输入联系电话"
          />
        </ElFormItem>
        <ElFormItem label="驾照等级">
          <ElInput
            v-model="driverForm.licenseLevel"
            placeholder="请输入驾照等级（如：C1、B2、A1）"
          />
        </ElFormItem>
        <ElFormItem label="紧急联系人">
          <ElInput
            v-model="driverForm.emergencyContact"
            placeholder="请输入紧急联系人"
          />
        </ElFormItem>
        <ElFormItem label="初次领证日期">
          <ElInput
            v-model="driverForm.firstLicenseDate"
            type="date"
            placeholder="请选择初次领证日期"
          />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="formVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleFormSubmit">确定</ElButton>
      </template>
    </ElDialog>

    <!-- 车辆分配弹框 -->
    <ElDialog
      v-model="assignVisible"
      title="分配车辆"
      width="600px"
      @close="assignVisible = false"
    >
      <div v-if="currentDriver" class="assign-content">
        <p class="assign-driver-info">
          当前为 <strong>{{ currentDriver.fullName }}</strong> 分配车辆
        </p>
        <ElCheckboxGroup v-model="selectedVehicleIds">
          <div class="vehicle-list">
            <ElCheckbox
              v-for="vehicle in availableVehicles"
              :key="vehicle.vehicleId"
              :label="vehicle.vehicleId"
              :disabled="
                vehicle.status === '已分配' &&
                vehicle.driverId !== currentDriver.driverId
              "
            >
              <div class="vehicle-item">
                <span class="license-plate">{{ vehicle.licensePlate }}</span>
                <span class="model">{{ vehicle.model }}</span>
                <span
                  class="status"
                  :class="[
                    vehicle.status === '已分配' ? 'assigned' : 'available',
                  ]"
                >
                  {{ vehicle.status }}
                </span>
              </div>
            </ElCheckbox>
          </div>
        </ElCheckboxGroup>
      </div>
      <template #footer>
        <ElButton @click="assignVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleAssignSubmit">确定分配</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
.driver-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 16px;
}

.action-card {
  margin-bottom: 16px;
}

.data-card {
  margin-bottom: 16px;
}

.status-active {
  font-weight: 500;
  color: #67c23a;
}

.status-inactive {
  font-weight: 500;
  color: #909399;
}

.assign-content {
  padding: 10px 0;
}

.assign-driver-info {
  margin-bottom: 15px;
  font-size: 14px;
  color: #606266;
}

.vehicle-list {
  max-height: 300px;
  overflow-y: auto;
}

.vehicle-item {
  display: flex;
  gap: 10px;
  align-items: center;
  margin: 5px 0;
}

.license-plate {
  min-width: 100px;
  font-weight: 500;
}

.model {
  min-width: 120px;
  color: #909399;
}

.status.assigned {
  font-size: 12px;
  color: #e6a23c;
}

.status.available {
  font-size: 12px;
  color: #67c23a;
}
</style>
